package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.BdmOrderItemVo;
import com.ruoyi.system.domain.vo.BdmOrderVo;
import com.ruoyi.system.domain.vo.BdmUserVo;
import com.ruoyi.system.domain.vo.UserOrderStatusCountVo;
import com.ruoyi.system.domain.vo.applet.*;
import com.ruoyi.system.enums.*;
import com.ruoyi.system.mapper.BdmBalanceChangeMapper;
import com.ruoyi.system.mapper.BdmOrderMapper;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.BdmOrder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-13
 */
@Slf4j
@Service
public class BdmOrderServiceImpl extends ServiceImpl<BdmOrderMapper, BdmOrder> implements IBdmOrderService {
    //订单
    @Autowired
    private BdmOrderMapper bdmOrderMapper;

    @Autowired
    //订单项
    private IBdmOrderItemService bdmOrderItemService;

    @Autowired
    //商品
    private IBdmGoodService bdmGoodService;

    @Autowired
    //用户等级
    private IBdmMemberRuleService bdmMemberRuleService;

    @Autowired
    //商品类型
    private IBdmGoodclassifyService bdmGoodclassifyService;

    @Autowired
    //用户
    private IBdmUserService bdmUserService;

    @Autowired
    //购物车
    private IBdmCartService bdmCartService;

    @Autowired
    //购买 vip礼包 或者 代理礼包 业务逻辑
    private IDistributionServiceImpl iDistributionService;

    @Autowired
    //用户 余额 积分 佣金 变动
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    //获取事务
    private SqlSessionTemplate sqlSessionTemplate;

    //云库存
    @Autowired
    private IBdmCloudInventoryService bdmCloudInventoryService;

    //物流发货
    @Autowired
    private IDistributionServiceImpl distributionService;

    @Autowired
    private IBdmOrderShipmentsService bdmOrderShipmentsService;

    //售后
    @Autowired
    private IBdmAfterSalesService bdmAfterSalesService;

    @Autowired
    private IBdmShareOutBonusLevelService iBdmShareOutBonusLevelService;

    @Autowired
    private IBdmRoyaltyRecordService iBdmRoyaltyRecordService;

    @Autowired
    private IBdmPayService bdmPayService;

    @Autowired
    private IBdmAgentGiftPackageService iBdmAgentGiftPackageService;

    @Autowired
    private IBdmCloudInventoryItemService iBdmCloudInventoryItemService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBdmUserService iBdmUserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private BdmUserMapper bdmUserMapper;

    @Autowired
    private IBdmCloudInventoryItemService bdmCloudInventoryItemService;


    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public BdmOrder selectBdmOrderById(String id) {
        return bdmOrderMapper.selectBdmOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param bdmOrder 订单
     * @return 订单
     */
    @Override
    public List<BdmOrder> selectBdmOrderList(BdmOrder bdmOrder) {
        return bdmOrderMapper.selectBdmOrderList(bdmOrder);
    }

    /**
     * 新增订单
     *
     * @param bdmOrder 订单
     * @return 结果
     */
    @Override
    public int insertBdmOrder(BdmOrder bdmOrder) {
        bdmOrder.setCreateTime(DateUtils.getNowDate());
        return bdmOrderMapper.insertBdmOrder(bdmOrder);
    }

    /**
     * 修改订单
     *
     * @param bdmOrder 订单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBdmOrder(BdmOrder bdmOrder) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        bdmOrder.setUpdateTime(DateUtils.getNowDate());

        if (ObjectUtils.isNotEmpty(bdmOrder) && ObjectUtils.isNotEmpty(bdmOrder.getOrderStatus()) && bdmOrder.getOrderStatus().equals(BdmOrderEnum.DISTRIBUTION.getType())) {
            //新增订单日志
            //-------------------新增订单操作日志-------------------
            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
            //新增订单操作日志
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(loginUser.getUsername());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(loginUser.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("商家发货");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.MERCHANT_DELIVERY.getType());
            bdmOrderShipments.add(bdmOrderShipment);
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束-----------------
        }
        return bdmOrderMapper.updateBdmOrder(bdmOrder);
    }

    @Override
    public int updateBdmOrder1(BdmOrder bdmOrder) throws Exception {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BdmOrder bdmOrder1 = bdmOrderMapper.selectBdmOrderById(bdmOrder.getId());
        BdmUserVo bdmUserVo = bdmUserMapper.selectUserByUserId(bdmOrder1.getUserId());
        bdmOrder1.setUpdateTime(DateUtils.getNowDate());

        if (ObjectUtils.isNotEmpty(bdmOrder1) && ObjectUtils.isNotEmpty(bdmOrder1.getOrderStatus()) && bdmOrder1.getOrderStatus().equals(BdmOrderEnum.DISTRIBUTION.getType())) {
            //新增订单日志
            //-------------------新增订单操作日志-------------------
            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
            //新增订单操作日志
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(loginUser.getUsername());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(loginUser.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("商家发货");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.MERCHANT_DELIVERY.getType());
            bdmOrderShipments.add(bdmOrderShipment);
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束-----------------
        }
        String appId = WxConfig.APP_ID;
        String secret = WxConfig.secret;
        String accessToken = getAccessToken(appId, secret);
        String mchId = "798633418";
//        String mchId="798633418";
//        // String transid="4200002823202508208786276655";
//        String outTradeNo =bdmOrder.getNativeId();
//        String accessToken=token;
//        String openid=openId;
//        String desc=bdmOrder.getGoodNames();
//        String expressCompany=bdmOrder.getLId();
//        String trackingNo=bdmOrder.getLcId();
//        JSONObject jsonObject = searchWxID(bdmOrder1.getId());
//        log.info("查询订单物流信息：{}", jsonObject);
//        if(jsonObject != null) {
//            String nativeId = jsonObject.getString("nativeId");
        String nativeId = bdmOrder1.getNativeId();
        uploadShippingInfo(mchId, nativeId, accessToken, bdmUserVo.getOpenId(), bdmOrder1.getGoodNames(), bdmOrder1.getLcId(), bdmOrder1.getLId());
//        }
        bdmOrder1.setOrderStatus(BdmOrderEnum.DISTRIBUTION.getType());
        return bdmOrderMapper.updateBdmOrder(bdmOrder1);
    }

    /**
     * 向微信上传订单物流信息
     *
     * @param mchId          商户号（微信支付分配）
     * @param outTradeNo     商户订单号 或 微信支付订单号（取决于 order_number_type）
     * @param accessToken    小程序调用凭证（注意要定时刷新）
     * @param openid         用户的 openid（付款用户）
     * @param desc           商品描述（例如：苹果手机一台）
     * @param expressCompany 快递公司编码（如：SF 表示顺丰）
     * @param trackingNo     快递单号
     */
    public void uploadShippingInfo(String mchId,
                                   String outTradeNo,
                                   String accessToken,
                                   String openid,
                                   String desc,
                                   String expressCompany,
                                   String trackingNo) {

        // 1. 构建请求地址（access_token 必须是小程序的，且有效）
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;

        // 2. 设置请求头：Content-Type 为 application/json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        // 3. 构建订单标识对象（order_key）
        JSONObject orderKey = new JSONObject();
        // 订单单号类型：1=商户单号（out_trade_no），2=微信支付订单号（transaction_id）
        orderKey.put("order_number_type", 2);
        orderKey.put("mchid", mchId);
        // 如果使用 transaction_id，则这里传微信支付单号
        orderKey.put("transaction_id", outTradeNo);
        // 如果使用商户单号模式：
        // orderKey.put("out_trade_no", outTradeNo);

        // 4. 构建单个商品的物流信息
        JSONObject shippingList = new JSONObject();
        shippingList.put("item_desc", desc);           // 商品描述
        shippingList.put("tracking_no", trackingNo);   // 物流单号
        shippingList.put("express_company", expressCompany); // 快递公司编码

        // 5. 构建付款人信息
        JSONObject payer = new JSONObject();
        payer.put("openid", openid);

        // 6. 组装请求参数
        JSONObject signObject = new JSONObject();
        JSONArray shipping_list = new JSONArray();
        shipping_list.add(shippingList);

        // 上传时间（必须是 ISO8601 格式，例如：2025-08-29T09:00:00+0800）
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String uploadTime = simpleDateFormat.format(System.currentTimeMillis());

        signObject.put("order_key", orderKey); // 订单标识
        signObject.put("delivery_mode", 1);    // 发货模式：1=统一发货，2=分拆发货
        signObject.put("logistics_type", 1);   // 物流方式：1=快递，2=同城配送，3=虚拟商品，4=自提
        signObject.put("shipping_list", shipping_list); // 物流明细
        signObject.put("upload_time", uploadTime);      // 上传时间
        signObject.put("payer", payer);                 // 用户信息

        // 7. 构建请求体
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(signObject, headers);

        // 8. 调用微信 API
        ResponseEntity<String> responseEntity =
                restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 9. 打印返回结果（可根据 errcode 判断是否成功）
        String body = responseEntity.getBody();
        System.out.println("微信返回结果：" + body);
        System.out.println("上传物流信息完成");

        // 10. 建议在这里解析返回结果：
        // JSONObject jsonObject = JSONUtil.parseObj(body);
        // String errcode = jsonObject.getString("errcode");
        // if (!"0".equals(errcode)) { ... } // 处理异常情况
    }


    public JSONObject searchWxID(String orderid) throws Exception {
        String APIKEY = "10819801";
        String PRIVATE_KEY = "43173548";
        JSONObject params = new JSONObject();
        String payParams =
                "nonceStr=effd910c69" +
                        "&outTradeNo=" + orderid +
                        "&terminalCode=" + APIKEY +
                        "&key=" + PRIVATE_KEY;
        String sign = Md5Utils.toHex(Md5Utils.md5(payParams));
        params.put("outTradeNo", orderid);
        params.put("nonceStr", "effd910c69");
        params.put("terminalCode", APIKEY);
        params.put("sign", sign);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(params);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange("https://www.yqdfpay.com/api/third/v2.0/transaction/detail", HttpMethod.POST, requestEntity, String.class);
        String body = responseEntity.getBody();
        JSONObject object = JSONObject.parseObject(body);
        if ("1".equals(object.getString("code"))) {
            //无此交易
            return null;
        } else {
            System.out.println(object.getString("data"));
            JSONObject payinfo = JSONObject.parseObject(object.getString("data"));
            return payinfo;
        }

    }

    public String getAccessToken(String appid, String secret) {
        // log.info("initAccessToken:开始运行...");
        String accessToken = null;
        //获取tokcen接口
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");

            //log.info("返回accessToken:"+accessToken);
            //log.info("initAccessToken:运行结束...");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessToken;

    }


    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteBdmOrderByIds(String[] ids) {
        return bdmOrderMapper.deleteBdmOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteBdmOrderById(String id) {
        return bdmOrderMapper.deleteBdmOrderById(id);
    }

    /**
     * 创建订单
     *
     * @param bdmOrderCreateDto
     * @return
     */
    @Override
    @Transactional
    public BdmOrder createOrder(BdmOrderCreateDto bdmOrderCreateDto) {
        //当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //购物车
        List<BdmCartDto> bdmCartDtos = bdmOrderCreateDto.getBdmCartDtos();
        //单个商品立即支付
        BdmGoodDto bdmGoodsDto = bdmOrderCreateDto.getBdmGoodsDto();
        //用户等级查询
        BdmMemberRule bdmMemberRule = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, user.getUserId()).one();
        //用户信息查询
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();
        if (ObjectUtils.isEmpty(bdmUser)) {
            throw new RuntimeException("用户异常");
        }

        //当前购买商品所需运费 TODO 目前默认运费后期需要改
        BigDecimal freight = bdmOrderCreateDto.getDeliveryCost();
        //总共要购买的商品 订单项
        List<BdmOrderItem> bdmOrderItems = new ArrayList<>();
        //单个购买
        if (!ObjectUtils.isEmpty(bdmGoodsDto)) {
            //查询库存
            BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, bdmGoodsDto.getId()).one();
            if (ObjectUtils.isEmpty(bdmGood)) {
                throw new RuntimeException("要购买的商品已下架");
            }
            Integer goodInventory = Integer.parseInt(bdmGood.getGoodInventory());
            if (goodInventory.compareTo(bdmGoodsDto.getNumber()) < 0) {
                throw new RuntimeException("商品" + bdmGood.getGoodName() + "库存不足");
            }
            BdmGoodDto bdmGoodDto = BeanUtil.copyProperties(bdmGood, BdmGoodDto.class);
            bdmGoodDto.setNumber(bdmGoodsDto.getNumber());
            //调取方法获取订单详情
            bdmOrderItems.add(this.getBdmOrderItem(bdmGoodDto, bdmMemberRule, bdmUser));
            if (bdmGood.getProductLevel() != null && bdmGood.getProductLevel() == 1) {
                verifyNumber(bdmGood.getInventoryVersion(), user.getUserId(), bdmGood.getId(), bdmOrderItems.stream().mapToInt(m -> Integer.parseInt(m.getGoodCount())).sum());
            }
        }
        //购物车购买 先查询商品
        if (!CollectionUtils.isEmpty(bdmCartDtos)) {
            //购物车中的商品id
            List<Long> BdmGoodId = bdmCartDtos.stream().map(BdmCartDto::getProductId).collect(Collectors.toList());
            //最新的商品
            List<BdmGood> bdmGoodList = bdmGoodService.lambdaQuery().in(BdmGood::getId, BdmGoodId).list();
            if (CollectionUtils.isEmpty(bdmGoodList)) {
                throw new RuntimeException("要购买的商品已下架");
            }
            Map<Long, BdmGood> bdmGoodMap = bdmGoodList.stream().collect(Collectors.toMap(BdmGood::getId, item -> item));
            for (BdmCartDto bdmCartDto : bdmCartDtos) {
                //如果有这个商品
                if (bdmGoodMap.containsKey(bdmCartDto.getProductId())) {
                    BdmGood bdmGood = bdmGoodMap.get(bdmCartDto.getProductId());
                    if (bdmGood.getProductLevel() != null && bdmGood.getProductLevel() == 1) {
                        verifyNumber(bdmGood.getInventoryVersion(), user.getUserId(), bdmGood.getId(), bdmCartDto.getCartNum());
                    }
                    if (bdmGood.getIsInitiate().equals(BdmGoodEnum.SOLDOUT.getType().toString())) {
                        throw new RuntimeException("商品" + bdmCartDto.getProductName() + "已下架");
                    }
                    Integer goodInventory = Integer.parseInt(bdmGood.getGoodInventory());
                    if (goodInventory.compareTo(bdmCartDto.getCartNum()) < 0) {
                        throw new RuntimeException("商品" + bdmCartDto.getProductName() + "库存不足");
                    }

                    BdmGoodDto bdmGoodDto = BeanUtil.copyProperties(bdmGood, BdmGoodDto.class);
                    bdmGoodDto.setNumber(bdmCartDto.getCartNum());
                    //调取方法获取订单详情
                    bdmOrderItems.add(this.getBdmOrderItem(bdmGoodDto, bdmMemberRule, bdmUser));
                    //没有
                } else {
                    throw new RuntimeException("要购买的商品" + bdmCartDto.getProductName() + "已下架");
                }
            }
        }


        Date nowDate = DateUtils.getNowDate();
        bdmOrderItems.forEach(item -> {
            item.setCreateTime(nowDate);
            //   计算订单项 的金额
            BigDecimal reduce = item.getGoodPrice();
            reduce.add(freight);


        });
        String goodNames = "";
        // 创建一个Random对象
        Random random = new Random();
        for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
            BdmGood good = bdmGoodService.getById(bdmOrderItem.getSupplierGoodId());
            if (good.getIntegralPrice() == null && good.getPointsRedemption().equals("2")) {

                // 生成一个随机数表示金额（以分为单位）
                int randomAmountInCents = random.nextInt(100) + 1; // 生成1到100之间的随机数

                // 使用BigDecimal来表示和处理金额
                BigDecimal oneCent = new BigDecimal("0.01");
                BigDecimal randomAmount = new BigDecimal(randomAmountInCents).multiply(oneCent);
                // 为配合小程序下单直接取的产品金额；暂时取消随机减
                // randomAmount=new BigDecimal("0.00");
                bdmOrderItem.setGoodPrice(bdmOrderItem.getGoodPrice().subtract(randomAmount));
            }
            goodNames = bdmOrderItems.stream().map(BdmOrderItem::getGoodName).collect(Collectors.joining(","));
        }
        //   计算订单项 的金额
        BigDecimal reduce = bdmOrderItems.stream().map(BdmOrderItem::getGoodPrice).reduce(BigDecimal.ZERO, BigDecimal::add);


        // 计算金额加上运费
        reduce = reduce.add(freight);
        //用户地址
        BdmReceiveAddress bdmReceiveAddress = bdmOrderCreateDto.getBdmReceiveAddress();
        if (ObjectUtils.isEmpty(bdmReceiveAddress) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getProvince()) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getCity()) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getDistrict()) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getDetail()) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getRealName()) ||
                ObjectUtils.isEmpty(bdmReceiveAddress.getPhone())
        ) {
            throw new RuntimeException("收货地址信息必填");
        }

        StringBuilder addr = new StringBuilder();
        //省
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getProvince())) {
            addr.append(bdmReceiveAddress.getProvince());
        }
        //市
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getCity())) {
            addr.append(bdmReceiveAddress.getCity());
        }
        //区
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getDistrict())) {
            addr.append(bdmReceiveAddress.getDistrict());
        }
        //详细地址
        if (StringUtils.isNotEmpty(bdmReceiveAddress.getDetail())) {
            addr.append(bdmReceiveAddress.getDetail());
        }
        //商品所需积分
        Long deductIntegral = bdmOrderItems.stream().mapToLong(item -> Long.parseLong(item.getDeductIntegral())).reduce(0, Long::sum);
        //购买商品获取积分
        Long gainIntegral = bdmOrderItems.stream().mapToLong(item -> Long.parseLong(item.getGainIntegral())).reduce(0, Long::sum);

        BdmOrder bdmOrder = BdmOrder.builder()
                .id(generateOrderNumber())//订单id
                .userId(user.getUserId())//用户id
                .userName(user.getUserName())//姓名
                .phoneNumber(user.getPhonenumber())//用户手机号
                .payMoney(reduce.setScale(2, BigDecimal.ROUND_DOWN).toString())//实付金额
                .deliveryCost(freight.toString())//配送费 TODO  目前配送费写死后期需要在后台设置
                .receiveName(bdmReceiveAddress.getRealName())//收货人姓名
                .receiveAddress(addr.toString()) //地址
                .receivePhonenum(bdmReceiveAddress.getPhone())//收货人电话
                .receiveLongitude(bdmReceiveAddress.getLongitude())//经度
                .receiveLatitude(bdmReceiveAddress.getLatitude())//纬度
                .createTime(DateUtils.getNowDate()) //创建时间
                .deductIntegral(deductIntegral.toString())//本单扣除积分
                .gainIntegral(gainIntegral.toString())//本单获取积分
                .remark(bdmOrderCreateDto.getRemark())//备注
                .orderType(BdmGoodEnum.MALL_ORDER.getType())//订单类型 商城订单
                .goodNames(goodNames)
                .build();
        //新增订单
        this.save(bdmOrder);

        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
        bdmOrderShipment.setUserName(bdmOrder.getUserName());
        bdmOrderShipment.setCreateTime(nowDate);
        bdmOrderShipment.setUserId(bdmOrder.getUserId());
        bdmOrderShipment.setSoId(bdmOrder.getId());
        bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户订单创建成功");
        bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.BUYER_ORDER.getType());
        bdmOrderShipments.add(bdmOrderShipment);
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //--------------------新增订单操作日志结束-------------------

        //填充订单id
        for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
            bdmOrderItem.setOrderId(bdmOrder.getId());
        }
        //新增订单明细
        bdmOrderItemService.saveBatch(bdmOrderItems);
        //批量扣减库存
        bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.SUB.getType());
        return bdmOrder;
    }

    //通用支付
    @Override
    @Transactional
    public synchronized AjaxResult balancePay(BdmOrderPayDto bdmOrderPayDto) {
        //防止一个订单执行两次
//        System.out.println("22222222222222222");
//        String  isnull=  redisCache.getCacheObject( bdmOrderPayDto.getOrderId());
//        if(isnull!=null){
//            System.out.println(isnull.toString());
//           // return AjaxResult.success(1);
//        }else{
//            redisCache.setCacheObject( bdmOrderPayDto.getOrderId(),"1");;
//        }
//        System.out.println("3333333333333333333333");
        BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, bdmOrderPayDto.getOrderId()).one();


        SysUser user = userService.selectUserById(bdmOrder.getUserId());
        Object cacheObject = redisCache.getCacheObject(user.getUserId().toString());
        if (cacheObject != null) {
            // 绑定用户
            // BdmUser bdmUser = iBdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();
            //  bdmUser.setParentId(Long.parseLong(cacheObject.toString()));
            //  分销的关系的绑定,是在第一次给平台奖励时绑定的；和推荐升级没有关系
            // bdmUser.setDistributionParentId(Long.parseLong(cacheObject.toString()));
            // iBdmUserService.updateBdmUser(bdmUser);
        }
        //查询订单
        System.out.println("444444444444444");

//        if (bdmOrder.getOrderStatus().equals(BdmOrderEnum.CLOSE.getType())) {
//            throw new GlobalException("订单超时已关闭");
//        }
        if (bdmOrder.getOrderStatus() > 0) {
            throw new GlobalException("该订单已支付");
        }
        //用户地址
        BdmReceiveAddress bdmReceiveAddress = bdmOrderPayDto.getBdmReceiveAddress();

        StringBuilder addr = new StringBuilder();

        if (!ObjectUtils.isEmpty(bdmReceiveAddress)) {
            //省
            if (StringUtils.isNotEmpty(bdmReceiveAddress.getProvince())) {
                addr.append(bdmReceiveAddress.getProvince());
            }
            //市
            if (StringUtils.isNotEmpty(bdmReceiveAddress.getCity())) {
                addr.append(bdmReceiveAddress.getCity());
            }
            //区
            if (StringUtils.isNotEmpty(bdmReceiveAddress.getDistrict())) {
                addr.append(bdmReceiveAddress.getDistrict());
            }
            //详细地址
            if (StringUtils.isNotEmpty(bdmReceiveAddress.getDetail())) {
                addr.append(bdmReceiveAddress.getDetail());
            }
        }

        //查询订单项
        List<BdmOrderItemVo> bdmOrderItemVos = bdmOrderItemService.getBdmOrderItems(bdmOrderPayDto.getOrderId());
        List<BdmOrderItem> bdmOrderItems = BeanUtil.copyToList(bdmOrderItemVos, BdmOrderItem.class);
        //查询用户信息
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();
        //判断用户
        if (ObjectUtils.isEmpty(bdmUser)) {
            throw new GlobalException("用户不存在");
        }
        //判断订单
        if (ObjectUtils.isEmpty(bdmOrder)) {
            throw new GlobalException("订单不存在");
        }
        //用户余额
        BigDecimal remainingSum = ObjectUtils.isEmpty(bdmUser.getRemainingSum()) ? new BigDecimal("0") : bdmUser.getRemainingSum();
        //用户总消费金额
        String totalConsumeMomey = StringUtils.isEmpty(bdmUser.getTotalConsumeMomey()) ? "0" : bdmUser.getTotalConsumeMomey();
        //用户总积分
        Long creditScore = Long.valueOf(StringUtils.isEmpty(bdmUser.getCreditScore()) ? "0" : bdmUser.getCreditScore());
        //订单扣减积分
        Long deductIntegral = Long.valueOf(StringUtils.isEmpty(bdmOrder.getDeductIntegral()) ? "0" : bdmOrder.getDeductIntegral());
        //订单增加积分
        Long gainIntegral = Long.valueOf(StringUtils.isEmpty(bdmOrder.getGainIntegral()) ? "0" : bdmOrder.getGainIntegral());


        //判断订单详情
        if (CollectionUtils.isEmpty(bdmOrderItems)) {
            throw new GlobalException("订单详情不存在");
        }
        //判断积分
        if (creditScore.compareTo(deductIntegral) < 0) {
            throw new GlobalException("账户积分不足");
        }
        //判断订单是否超时
        long time = bdmOrder.getCreateTime().getTime() + BdmOrderEnum.TIMEOUT.getType() * 1000 * 60; //订单下单时间
        long currentTime = System.currentTimeMillis();//当前时间
        if (currentTime > time) {
            //修改订单状态
            bdmOrder.setUpdateTime(DateUtils.getNowDate());//修改时间
            bdmOrder.setOrderStatus(BdmOrderEnum.CLOSE.getType());//项目状态 已关闭
            bdmOrder.setReceiveName(bdmReceiveAddress.getRealName());//收货人姓名
            if (StringUtils.isNotEmpty(addr.toString())) {
                bdmOrder.setReceiveAddress(addr.toString()); //地址
            }
            bdmOrder.setReceivePhonenum(bdmReceiveAddress.getPhone());//收货人电话
            bdmOrder.setReceiveLongitude(bdmReceiveAddress.getLongitude());//经度
            bdmOrder.setReceiveLatitude(bdmReceiveAddress.getLatitude());//纬度
            this.updateById(bdmOrder);//修改订单状态
            bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());//回滚库存
            //-------------------新增订单操作日志-------------------
            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
            //新增订单操作日志
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户订单超时未支付");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.ORDER_CLOSURE.getType());
            bdmOrderShipments.add(bdmOrderShipment);
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束-----------------

            return AjaxResult.error("订单超时请重新下单");
        }
        Date nowDate = DateUtils.getNowDate();
        //----------------------清空购物车------------------------
        //清空购物车
        List<String> goodIds = bdmOrderItems.stream().map(BdmOrderItem::getSupplierGoodId).collect(Collectors.toList());//商品id
        List<BdmCart> bdmCarts = bdmCartService.lambdaQuery()//购物车
                .eq(BdmCart::getUserId, user.getUserId())//当前用户
                .in(BdmCart::getProductId, goodIds)//商品id
                .list();

        if (!CollectionUtils.isEmpty(bdmCarts)) {
            List<Long> BdmCartIds = bdmCarts.stream().map(BdmCart::getId).collect(Collectors.toList());
            bdmCartService.removeBatchByIds(BdmCartIds);
        }
        //----------------------清空购物车结束------------------------

        // 余额 积分 变动 集合
        List<BdmBalanceChange> bdmBalanceChanges = new ArrayList<>();
        //---------------------修改用户信息状态/支付----------------------
        //余额
        if (bdmOrderPayDto.getPayMode().equals(BdmOrderEnum.BALANCE.getType())) {
            //判断支付密码
//            if (StringUtils.isEmpty(bdmUser.getPayCode())) {
//                throw new RuntimeException("请先设置支付密码");
//            }
            //比对支付密码
//            if (ObjectUtils.isEmpty(bdmOrderPayDto.getPayCode()) || !SecurityUtils.matchesPassword(bdmOrderPayDto.getPayCode(), bdmUser.getPayCode())) {
//                throw new RuntimeException("支付密码错误");
//            }
            //判断余额
            if (remainingSum.compareTo(new BigDecimal(bdmOrder.getPayMoney())) < 0) {
                throw new RuntimeException("账户余额不足");
            }
            //减少余额
            bdmUser.setRemainingSum(remainingSum.subtract(new BigDecimal(bdmOrder.getPayMoney())));
            //记录用户余额积分变动
            bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                    user.getUserId(),
                    bdmOrder.getId(),
                    bdmOrder.getPayMoney(),
                    remainingSum.toString(),
                    String.valueOf(remainingSum.subtract(new BigDecimal(bdmOrder.getPayMoney()))),
                    Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                    BdmBalanceChangeEnum.CONSUMPTION_DEDUCTION.getDescription()
            ));

            // TODO 有其他支付方式在后面接
        } else if (bdmOrderPayDto.getPayMode().equals(BdmOrderEnum.THIRD_PARTY.getType())) {
            //第三方 支付 如果没有抛异常就说明支付成功了 抛异常就回滚，这个已经改了，支付成功才会走这里，所以这一步不需要
            // bdmPayService.selectPay(bdmOrder);

        } else {
            throw new GlobalException("支付方式不存在");
        }


        bdmUser.setTotalConsumeMomey(new BigDecimal(totalConsumeMomey).add(new BigDecimal(bdmOrder.getPayMoney())).toString());//累计消费金额增加
        bdmUser.setCreditScore(String.valueOf(creditScore + gainIntegral - deductIntegral));//结算积分
        //  bdmUser.setDistributionParentId(bdmUser.getParentId());//建立关系 分销人id改为上级id
        bdmUserService.updateById(bdmUser);
        //---------------------修改用户信息/支付结束----------------------

        //调用购买礼包 升级接口
        List<BdmGood> bdmGoodList = bdmGoodService.lambdaQuery().in(BdmGood::getId, goodIds).list();//本次购买的商品列表
        //购买的数量
        Map<String, BdmOrderItem> bdmOrderItemMap = bdmOrderItems.stream().collect(Collectors.toMap(BdmOrderItem::getSupplierGoodId, item -> item));


        //----------------升级前记录当前用户等级----------------
        BdmMemberRule one = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmUser.getSysUserid()).one();
        if (!ObjectUtils.isEmpty(one)) {
            bdmOrder.setBeforMemberLevel(one.getMemberLevel());
            bdmOrder.setBeforMemberName(one.getMemberName());
            bdmOrder.setBeforMemberAgencyLevel(one.getMemberAgencyLevel());
            bdmOrder.setBeforMemberAgencyLevelName(one.getMemberAgencyLevelName());
        }
        //-------------------------升级-------------------------
        for (BdmGood bdmGood : bdmGoodList) {
            //升级
            BdmOrderItem bdmOrderItem = bdmOrderItemMap.get(bdmGood.getId().toString());
            int number = Integer.parseInt(bdmOrderItem.getGoodCount());
            for (int i = 0; i < number; i++) {
                if (ObjectUtils.isNotEmpty(bdmGood.getProductLevel())) {
                    if (bdmGood.getProductLevel().equals(BdmMemberRuleEnum.VIP.getLevel())) {
                        iDistributionService.vipAward(user.getUserId(), bdmOrder.getId(), bdmGood.getId());
                    } else if (bdmGood.getProductLevel().compareTo(BdmMemberRuleEnum.SHOPKEEPER.getLevel()) >= 0) {
                        iDistributionService.agencyAward(user.getUserId(), bdmOrder.getId(), bdmGood.getId());
                        insertCloudInventory(bdmGood.getId(), user.getUserId(), bdmOrder.getId());
                    }
                }
            }

            Long virtualSales = StringUtils.isEmpty(bdmGood.getVirtualSales()) ? 0L : Long.parseLong(bdmGood.getVirtualSales());
            Long goodCount = Long.parseLong(bdmOrderItemMap.get(bdmGood.getId().toString()).getGoodCount());
            //增加销量
            bdmGood.setVirtualSales(String.valueOf(virtualSales + goodCount));
        }
        //修改商品销量
        bdmGoodService.updateBatchById(bdmGoodList);

        // 查询当前用户信息
        BdmUserVo bdmUserVo = iDistributionService.getBdmUser(user.getUserId());
        // 计算上级的下属人数,如果人数达到两人,那么自动升级为svip,此时升级后的svip下属归svip升级前的上级,如果上级是vip,那么不进行关联
        iDistributionService.whetherUpgrade(bdmUserVo.getDistributionParentId(), BdmMemberRuleEnum.VIP.getLevel(), 1, user.getUserId());
        //-------------------------升级结束-------------------------

        //-----------------------插入 余额 积分 变动 明细表------------------------

        //增加积分
        if (gainIntegral > 0) {
            bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                    user.getUserId(),
                    bdmOrder.getId(),
                    gainIntegral.toString(),
                    creditScore.toString(),
                    String.valueOf(creditScore + gainIntegral),
                    Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                    BdmBalanceChangeEnum.POINT_GIVEAWAY.getDescription()
            ));
        }
        //减少积分
        if (deductIntegral > 0) {
            bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                    user.getUserId(),
                    bdmOrder.getId(),
                    deductIntegral.toString(),
                    creditScore.toString(),
                    String.valueOf(creditScore - deductIntegral),
                    Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                    BdmBalanceChangeEnum.POINT_DEDUCTION.getDescription()
            ));
        }


        bdmBalanceChangeService.saveBatch(bdmBalanceChanges);
        //-----------------------插入 余额 积分 变动 明细表 结束------------------------

        //添加云库存
        bdmCloudInventoryService.addBdmCloudInventory(bdmOrderItems, bdmUser);


        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();

        BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
        bdmOrderShipment.setUserName(bdmOrder.getUserName());
        bdmOrderShipment.setCreateTime(nowDate);
        bdmOrderShipment.setUserId(bdmOrder.getUserId());
        bdmOrderShipment.setSoId(bdmOrder.getId());
        bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户订单支付成功");
        bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.Buyer_Is_payment.getType());
        bdmOrderShipments.add(bdmOrderShipment);
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束-----------------

        //发货
        this.deliverGoods(bdmOrderItemVos, bdmOrder, BdmOrderEnum.BALANCE.getDescription());

        //修改订单状态
        bdmOrder.setUpdateTime(nowDate);//修改时间
        bdmOrder.setOrderStatus(BdmOrderEnum.SHIPMENTS.getType());//项目状态 待发货
        bdmOrder.setPaymentTime(nowDate);//支付时间
        bdmOrder.setPayType(bdmOrderPayDto.getPayMode());//支付方式
        bdmOrder.setFakeId(bdmOrderPayDto.getFakeId());
        bdmOrder.setNativeId(bdmOrderPayDto.getNativeId());
        bdmOrder.setTransactionId(bdmOrderPayDto.getNativeId());

        this.updateById(bdmOrder);
        redisCache.deleteObject(user.getUserId().toString());
        return AjaxResult.success(bdmOrder.getId());
    }


    /**
     * 发货                                         订单项详情                 订单            支付方式
     */
    @Override
    public void deliverGoods(List<BdmOrderItemVo> bdmOrderItemVos, BdmOrder bdmOrder, String payType) {
        log.info("发货开始=================================");
        //发货
        ArrayList<BdmOrdersUploadDto> bdmOrdersUploadDtos = new ArrayList<>();
        //筛选不是云库存的发货
//        List<BdmOrderItemVo> notCloudInventory = bdmOrderItemVos.stream().filter(item -> !((item.getGoodTypeName().equals(BdmGoodEnum.ONE_GRADE.getDescription())
//                || item.getGoodTypeName().equals(BdmGoodEnum.GIFT_PACKS.getDescription())) && DefaultZeroValueUtil.getValue(item.getDeductIntegral()).equals("0"))
//        ).collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(notCloudInventory)) {
//            return;
//        }
        BdmOrdersUploadDto bdmOrdersUploadDto = new BdmOrdersUploadDto();
        bdmOrdersUploadDto.setShop_id(16515278);
        bdmOrdersUploadDto.setSo_id(bdmOrder.getId());
        bdmOrdersUploadDto.setOrder_date(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", bdmOrder.getCreateTime()));
        bdmOrdersUploadDto.setShop_buyer_id(bdmOrder.getUserName());
        bdmOrdersUploadDto.setReceiver_address(bdmOrder.getReceiveAddress());
        bdmOrdersUploadDto.setReceiver_name(bdmOrder.getReceiveName());
        bdmOrdersUploadDto.setReceiver_phone(bdmOrder.getReceivePhonenum());
        bdmOrdersUploadDto.setPay_amount(new BigDecimal(bdmOrder.getPayMoney()));
        bdmOrdersUploadDto.setFreight(Integer.parseInt(bdmOrder.getDeliveryCost()));
        ArrayList<BdmOrderItemsDto> bdmOrderItemsDtos = new ArrayList<>();
        for (BdmOrderItemVo bdmOrderItem : bdmOrderItemVos) {
            BdmOrderItemsDto bdmOrderItemsDto = new BdmOrderItemsDto();
            bdmOrderItemsDto.setSku_id(bdmOrderItem.getProductCode());
            bdmOrderItemsDto.setShop_sku_id(bdmOrderItem.getShopSkuId());
            bdmOrderItemsDto.setAmount(bdmOrderItem.getGoodPrice());
            bdmOrderItemsDto.setBase_price(bdmOrderItem.getRetailPrice());
            bdmOrderItemsDto.setQty(Integer.parseInt(bdmOrderItem.getGoodCount()));
            bdmOrderItemsDto.setName(bdmOrderItem.getGoodName());
            bdmOrderItemsDto.setOuter_oi_id(bdmOrderItem.getSupplierGoodId());
            bdmOrderItemsDtos.add(bdmOrderItemsDto);
        }
        bdmOrdersUploadDto.setItems(bdmOrderItemsDtos);
        BdmPayDto bdmPayDto = new BdmPayDto();
        bdmPayDto.setOuter_pay_id(bdmOrder.getId());
        bdmPayDto.setPay_date(DateUtils.getDate());
        bdmPayDto.setPayment(payType);
        bdmPayDto.setSeller_account(bdmOrder.getPhoneNumber());
        bdmPayDto.setBuyer_account("688");
        bdmPayDto.setAmount(new BigDecimal(bdmOrder.getPayMoney()));
        bdmOrdersUploadDto.setPay(bdmPayDto);
        bdmOrdersUploadDtos.add(bdmOrdersUploadDto);
        BdmOrdersUploadDataDto logistics = distributionService.logistics(bdmOrdersUploadDtos);
        bdmOrder.setOId(logistics.getO_id().toString());
        //存聚水潭id
        this.updateById(bdmOrder);
        log.info("发货结束=================================");
    }


    /**
     * 用户取消退单
     */
    @Override
    @Transactional
    public AjaxResult cancelRefund(String orderId) {
        List<BdmAfterSales> bdmAfterSalesList = bdmAfterSalesService.lambdaQuery().eq(BdmAfterSales::getOrderCode, orderId).list();

        StringBuilder stringBuilder = new StringBuilder();
        for (BdmAfterSales bdmAfterSales : bdmAfterSalesList) {
            //后台已经退款完成的订单 无法取消
            if (bdmAfterSales.getState().equals(BdmAfterSalesEnum.COMPLETED.getType()) ||
                    bdmAfterSales.getState().equals(BdmAfterSalesEnum.USER_CANCELED.getType()) ||
                    bdmAfterSales.getState().equals(BdmAfterSalesEnum.PLATFORM_CANCELED.getType())
            ) {
                stringBuilder.append(bdmAfterSales.getOrderItemCode() + ',');
                continue;
            }


            bdmAfterSales.setState(BdmAfterSalesEnum.USER_CANCELED.getType());
            bdmAfterSales.setProcessingTime(DateUtils.getNowDate());
            BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, bdmAfterSales.getOrderCode()).one();
            //-------------------新增订单操作日志-------------------
            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
            //新增订单操作日志
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("用户取消退单" + bdmOrder.getId());
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.THE_USER_CANCELS_THE_REFUND.getType());
            bdmOrderShipments.add(bdmOrderShipment);
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束-----------------
            bdmAfterSalesService.updateById(bdmAfterSales);

            //回退订单状态到用户申请退单前
            bdmOrder.setOrderStatus(bdmAfterSales.getPreOrderStatus());
            this.updateById(bdmOrder);
        }
        if (StringUtils.isNotEmpty(stringBuilder)) {
            return AjaxResult.success("订单状态已经改变，无法再次申请，请刷新页面。");
        }

        return AjaxResult.success("取消成功");

    }

    /**
     * 查看是不是部分退单
     */
    @Override
    public int countChargeback(String orderId) {
        return bdmOrderMapper.countChargeback(orderId);

    }


    /**
     * 查询订单列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmOrderVo> selectPageOrder(BdmOrderDto dto) {
        List<BdmOrderVo> bdmOrderVos = baseMapper.selectPageOrder(dto);
        //关闭超时订单
        this.closeOrder();
        return bdmOrderVos;
    }

    /**
     * 销售数据
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Integer> countMarketData(BdmMemberRuleDto dto) {
        return baseMapper.countMarketData(dto);
    }

    /**
     * 销售数据成交订单时间列表
     *
     * @return
     */
    @Override
    public List<Map<String, String>> selectMarketOrderData(BdmMemberRuleDto dto) {
        return baseMapper.selectMarketOrderData(dto);
    }

    /**
     * 数据概况 用户数 订单数 商品数 统计
     *
     * @return
     */
    @Override
    public List<Map<String, String>> selectUserNumberAndOrderNumberProductNumber(BdmMemberRuleDto dto) {
        return baseMapper.selectUserNumberAndOrderNumberProductNumber(dto);
    }

    /**
     * 商品销售额top前十
     *
     * @return
     */
    @Override
    public List<Map<String, String>> marketProductTop() {
        return baseMapper.marketProductTop();
    }

    /**
     * 用户支付金额top前十
     *
     * @return
     */
    @Override
    public List<Map<String, String>> userPayMoneyTop() {
        return baseMapper.userPayMoneyTop();
    }

    /**
     * 总裁驾驶窗首页数据
     *
     * @return
     */
    @Override
    public List<Map<String, String>> bossData() {
        return baseMapper.bossData();
    }

    /**
     * 根据当前用户查询订单列表
     *
     * @return
     */
    @Override
    public List<AppletBdmOrderVo> listByUser(BdmOrderDto bdmOrderDto) {
        List<AppletBdmOrderVo> appletBdmOrderVos = new ArrayList<>();
        List<BdmOrder> bdmOrders = bdmOrderMapper.selectBdmorder(bdmOrderDto);
        if (CollectionUtils.isEmpty(bdmOrders)) {
            return appletBdmOrderVos;
        }
        List<String> orderIds = bdmOrders.stream().map(BdmOrder::getId).collect(Collectors.toList());
        bdmOrderDto.setOrderIds(orderIds);
        appletBdmOrderVos = bdmOrderMapper.listByUser(bdmOrderDto);
        return appletBdmOrderVos;
    }

    //根据商品 和用户等级 返回订单详情
    private BdmOrderItem getBdmOrderItem(BdmGoodDto bdmGoodDto, BdmMemberRule bdmMemberRule, BdmUser bdmUser) {
        BigDecimal price = bdmGoodDto.getRetailPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
        if (ObjectUtils.isNotEmpty(bdmMemberRule) && ObjectUtils.isEmpty(bdmGoodDto.getProductLevel())) {
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.VIP.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getVipPrice())) { //vip
                price = bdmGoodDto.getVipPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel()) && bdmMemberRule.getMemberLevel().equals(BdmMemberRuleEnum.SVIP.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getSvipPrice())) {//svip
                price = bdmGoodDto.getSvipPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.SHOPKEEPER.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getSharePrice())) {//共享
                price = bdmGoodDto.getSharePrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.LAIN_CHANG.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getJoinPrice())) {//联创
                price = bdmGoodDto.getJoinPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.OPERATION.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getOperationsPrice())) {//运营
                price = bdmGoodDto.getOperationsPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel()) && bdmMemberRule.getMemberAgencyLevel().equals(BdmMemberRuleEnum.BOSS.getLevel()) && ObjectUtils.isNotEmpty(bdmGoodDto.getPresidentPrice())) {//总裁
                price = bdmGoodDto.getPresidentPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
            }
        }
        //此项获取积分
        Long gainIntegral = StringUtils.isEmpty(bdmGoodDto.getBounsValue()) ? 0L : Long.parseLong(bdmGoodDto.getBounsValue()) * bdmGoodDto.getNumber();
        //此项扣除积分
        Long deductIntegral = 0L;

        //如果是积分兑换 算上兑换价
        if (ObjectUtils.isNotEmpty(bdmGoodDto) && bdmGoodDto.getPointsRedemption().equals(BdmGoodEnum.DEDUCTION.getType().toString())) {//积分兑换

            if (ObjectUtils.isNotEmpty(bdmGoodDto) && bdmGoodDto.getRedemptionSet().equals(BdmGoodEnum.INTEGRAL_MONEY.getType().toString())) {//积分加金额
                price = bdmGoodDto.getIntegralPrice().multiply(new BigDecimal(bdmGoodDto.getNumber()));
                deductIntegral = StringUtils.isEmpty(bdmGoodDto.getPointsUse()) ? 0L : Long.parseLong(bdmGoodDto.getPointsUse()) * bdmGoodDto.getNumber();
            }

            if (ObjectUtils.isNotEmpty(bdmGoodDto) && bdmGoodDto.getRedemptionSet().equals(BdmGoodEnum.WHOLE_INTEGRAL.getType().toString())) {//全积分兑换 不用钱
                price = new BigDecimal(0);
                deductIntegral = StringUtils.isEmpty(bdmGoodDto.getPointsUse()) ? 0L : Long.parseLong(bdmGoodDto.getPointsUse()) * bdmGoodDto.getNumber();
            }

        }
        //更新积分
        bdmUser.setCreditScore(String.valueOf(Long.parseLong(bdmUser.getCreditScore()) - deductIntegral));

        return BdmOrderItem.builder()
                .goodTypeId(bdmGoodDto.getClassOneId())//商品类型id
                .goodTypeName(bdmGoodDto.getClassOneName())//商品类型名称
                .supplierGoodId(bdmGoodDto.getId().toString())//供应商商品id
                .goodName(bdmGoodDto.getGoodName())//商品名称
                .goodPrice(price)//价格
                .goodCount(bdmGoodDto.getNumber().toString())//数量
                .gainIntegral(gainIntegral.toString())//此项获取积分
                .deductIntegral(deductIntegral.toString())//此项扣除积分
                .remarks("")
                .build();
    }


    //生成订单号
    @Override
    public String generateOrderNumber() {
        // 获取当前时间并格式化
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));

        String uuid = IdUtil.simpleUUID();
        // 取UUID的后几位作为随机部分
        String randomPart = uuid.substring(10, 15);
        // 拼接时间戳和随机部分
        return "BDM" + timestamp + randomPart;
    }

    /**
     * 小程序我的订单列表
     *
     * @param mineOrderDto
     * @return
     */
    @Override
    public List<AppletOrderListVo> selectAppletOrderList(MineOrderDto mineOrderDto) {
        mineOrderDto.setUserId(SecurityUtils.getUserId());
        List<AppletOrderListVo> orderListVo = new ArrayList<>();
        List<BdmOrder> orderList = bdmOrderMapper.selectAppletOrderList(mineOrderDto);
        if (StringUtils.isNotEmpty(orderList)) {
            List<String> orderIds = orderList.stream().map(BdmOrder::getId).distinct().collect(Collectors.toList());
            List<AppletOrderItemVo> orderItemList = bdmOrderItemService.selectBdmOrderItemByIds(orderIds);
            if (StringUtils.isNotEmpty(orderItemList)) {
                Map<String, List<AppletOrderItemVo>> itemMap = orderItemList.stream().collect(Collectors.groupingBy(AppletOrderItemVo::getOrderId));
                for (BdmOrder order : orderList) {
                    AppletOrderListVo vo = new AppletOrderListVo();
                    BeanUtil.copyProperties(order, vo);
                    vo.setOrderId(order.getId());
                    vo.setPayMoney(order.getPayMoney());
                    vo.setOrderStatus(BdmOrderEnum.getTypeName(order.getOrderStatus()));
                    vo.setBdmGoodVoList(itemMap.get(order.getId()));
                    orderListVo.add(vo);
                }
            }
        }
        return orderListVo;
    }


    /**
     * 退款
     *
     * @param bdmBalanceChanges 查询的变动信息
     */
    public void rollBackMoney(List<BdmBalanceChange> bdmBalanceChanges) {

        //获取sqlSession
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        //获取 库存和积分mapper
        BdmBalanceChangeMapper balanceChangeMapper = sqlSession.getMapper(BdmBalanceChangeMapper.class);
        try {
            //回库存
            for (BdmBalanceChange balanceChange : bdmBalanceChanges) {
                balanceChange.setAddOrSubtract(balanceChange.getAddOrSubtract() == 1L ? 2L : 1L);
                balanceChange.setBusinessType(balanceChange.getVariationType() == 1L ? "退款-订单余额回退" : balanceChange.getVariationType() == 2L ? "退款-订单积分回退" : "退款-订单佣金回退");
                balanceChange.setCreateBy(SecurityUtils.getUserId().toString());
                balanceChange.setCreateTime(DateUtils.getNowDate());
                balanceChange.setVariationBefore(balanceChange.getVariationAfter());
                balanceChange.setVariationAfter(new BigDecimal(balanceChange.getVariationAfter()).add(new BigDecimal(balanceChange.getVariation())).toString());
                int i = balanceChangeMapper.insertBdmBalanceChange(balanceChange);
                if (i == 0) {
                    throw new RuntimeException("操作失败请联系管理员");
                }
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 十五天自动收货
     */
    @Override
    @Transactional
    public void takeDeliveryOfGoods() {
        int day = 15;
        List<String> orderByOrderStatus1 = baseMapper.getOrderByOrderStatus(day);
        for (String orderByOrderStatus : orderByOrderStatus1) {
            BdmOrderDto bdmOrderDto = new BdmOrderDto();
            bdmOrderDto.setOrderId(orderByOrderStatus);
            autoReceivingGoods(bdmOrderDto);
        }
        baseMapper.takeDeliveryOfGoods(day);
    }

    /**
     * 获取订单统计信息
     *
     * @param userId
     */
    @Override
    public AjaxResult getOrderStatistics(Long userId) {
        // 数据库查询已有状态统计
//        List<UserOrderStatusCountVo> userOrderStatusCountVos = bdmOrderMapper.selectOrderStatusCount(userId);
//        // 用 Map 快速查找已有状态
//        Map<Integer, UserOrderStatusCountVo> statusMap = userOrderStatusCountVos.stream()
//                .collect(Collectors.toMap(UserOrderStatusCountVo::getOrderStatus, vo -> vo));
        // 定义所有状态
        List<Integer> allStatuses = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
        List<UserOrderStatusCountVo> resultList = new ArrayList<>();
        for (Integer allStatus : allStatuses) {
            BdmOrderDto bdmOrderDto = new BdmOrderDto();
            bdmOrderDto.setUserId(userId);
            bdmOrderDto.setOrderStatus(allStatus);
            List<AppletBdmOrderVo> appletBdmOrderVos = listByUser(bdmOrderDto);
            UserOrderStatusCountVo userOrderStatusCountVo = new UserOrderStatusCountVo();
            userOrderStatusCountVo.setOrderStatus(allStatus);
            userOrderStatusCountVo.setCount(appletBdmOrderVos.size());
            resultList.add(userOrderStatusCountVo);
        }
        // 补全不存在的状态
//        for (Integer status : allStatuses) {
//            UserOrderStatusCountVo userOrderStatusCountVo = new UserOrderStatusCountVo();
//            userOrderStatusCountVo.setOrderStatus(status);
//            userOrderStatusCountVo.setCount(0L);
//            resultList.add(statusMap.getOrDefault(status, userOrderStatusCountVo));
//        }
        return AjaxResult.success(resultList);
    }


    /**
     * 订单退货
     * 1. 商家还未发货 直接退
     * 2. 商家已发货 等待买家退货再退款
     *
     * @param bdmOrderDto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult chargeback(BdmOrderDto bdmOrderDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<BdmOrderItem> bdmOrderItems = bdmOrderItemService.lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(bdmOrderDto.getOrderId()), BdmOrderItem::getOrderId, bdmOrderDto.getOrderId())
                .eq(ObjectUtils.isNotEmpty(bdmOrderDto.getOrderItemId()), BdmOrderItem::getId, bdmOrderDto.getOrderItemId())
                .list();
        BdmOrder one = this.lambdaQuery().eq(BdmOrder::getId, bdmOrderDto.getOrderId()).one();
        if (one.getOrderStatus().equals(BdmOrderEnum.SHIPMENTS.getType())) {
            bdmAfterSalesService.refundOrder(bdmOrderDto.getOrderId());
        } else {
            if (one.getOrderStatus().equals(BdmOrderEnum.PARTIAL_REFUND.getType())) {
                throw new RuntimeException("该订单已经在退货申请中无法退货");
            }

            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                //新增售后记录
                BdmAfterSales bdmAfterSales = new BdmAfterSales();
                bdmAfterSales.setOrderCode(bdmOrderItem.getOrderId());//订单号
                bdmAfterSales.setOrderItemCode(bdmOrderItem.getId());//订单项id
                bdmAfterSales.setRefundAmount(bdmOrderItem.getGoodPrice());//退款金额
                bdmAfterSales.setCreateTime(DateUtils.getNowDate());//创建时间
                bdmAfterSales.setServiceType(bdmOrderDto.getServiceType());//服务类型 0仅退款 1退货退款
                bdmAfterSales.setReasons(bdmOrderDto.getExplains());//申请原因
                bdmAfterSales.setExplains(bdmOrderDto.getChargebackReason());//说明
                bdmAfterSales.setState(BdmAfterSalesEnum.PROCESSING.getType()); //处理中
                bdmAfterSales.setPreOrderStatus(one.getOrderStatus());//记录订单状态
                bdmAfterSales.setUserId(loginUser.getUserId());//用户id
                bdmAfterSalesService.save(bdmAfterSales);
                //新增订单日志
                //-------------------新增订单操作日志-------------------
                List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
                //新增订单操作日志
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(loginUser.getUsername());
                bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
                bdmOrderShipment.setUserId(loginUser.getUserId());
                bdmOrderShipment.setSoId(bdmOrderItem.getOrderId());
                bdmOrderShipment.setParticulars("用户申请退单商品" + bdmOrderItem.getGoodName());
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.PLATFORM_PROCESSING.getType());
                bdmOrderShipments.add(bdmOrderShipment);
                //新增订单操作日志
                bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
                //-------------------新增订单操作日志结束-----------------
                //修改订单状态
                if (ObjectUtils.isEmpty(one)) {
                    throw new RuntimeException("订单不存在");
                }
                one.setOrderStatus(BdmOrderEnum.PARTIAL_REFUND.getType());
                this.updateById(one);


            }
        }
        return AjaxResult.success();
    }

    /**
     * 订单确认收货
     *
     * @param bdmOrderDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int receivingGoods(BdmOrderDto bdmOrderDto) {

        BdmOrder order = new BdmOrder();
        order.setId(bdmOrderDto.getOrderId());
        order.setOrderStatus(4L);
        order.setReceiveTime(DateUtils.getNowDate());
        order.setUpdateTime(DateUtils.getNowDate());


        BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, bdmOrderDto.getOrderId()).one();
        if (ObjectUtils.isEmpty(bdmOrder)) {
            throw new RuntimeException("订单不存在");
        }

        if (!(bdmOrder.getOrderStatus().equals(BdmOrderEnum.GATHER.getType()) || bdmOrder.getOrderStatus().equals(BdmOrderEnum.DISTRIBUTION.getType()))) {
            throw new RuntimeException("当前状态不可确认收货");
        }

        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        //新增订单操作日志
        if (!ObjectUtils.isEmpty(bdmOrder)) {
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            //bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("订单号为：" + bdmOrder.getId() + " 用户确认收货");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.COMPLETE_TRANSACTION.getType());
            bdmOrderShipments.add(bdmOrderShipment);
        }
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束------------------

        // 增加分红奖金池金额
        iBdmShareOutBonusLevelService.addShareOutBonusLevelMoney(bdmOrderDto.getOrderId());
        // 查询当前订单是否存在上级分佣
        iBdmRoyaltyRecordService.selectLeaderBrokerage(bdmOrderDto.getOrderId());
        return bdmOrderMapper.updateBdmOrder(order);
    }

    /**
     * 订单确认收货
     *
     * @param bdmOrderDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void autoReceivingGoods(BdmOrderDto bdmOrderDto) {

        BdmOrder order = new BdmOrder();
        order.setId(bdmOrderDto.getOrderId());
        order.setOrderStatus(4L);
        order.setReceiveTime(DateUtils.getNowDate());
        order.setUpdateTime(DateUtils.getNowDate());

        BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, bdmOrderDto.getOrderId()).one();
        if (ObjectUtils.isEmpty(bdmOrder)) {
            throw new RuntimeException("订单不存在");
        }

        if (!(bdmOrder.getOrderStatus().equals(BdmOrderEnum.GATHER.getType()) || bdmOrder.getOrderStatus().equals(BdmOrderEnum.DISTRIBUTION.getType()))) {
            throw new RuntimeException("当前状态不可确认收货");
        }

        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        //新增订单操作日志
        if (!ObjectUtils.isEmpty(bdmOrder)) {
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            //bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setUserName("系统自动确认收货");
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("订单号为：" + bdmOrder.getId() + " 用户确认收货");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.COMPLETE_TRANSACTION.getType());
            bdmOrderShipments.add(bdmOrderShipment);
        }
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束------------------

        // 增加分红奖金池金额
        iBdmShareOutBonusLevelService.addShareOutBonusLevelMoney(bdmOrderDto.getOrderId());
        // 查询当前订单是否存在上级分佣
        iBdmRoyaltyRecordService.selectLeaderBrokerage(bdmOrderDto.getOrderId());
        bdmOrderMapper.updateBdmOrder(order);
    }

    /**
     * 修改未支付超时的订单为已关闭
     */
    @Override
    @Transactional
    public void closeOrder() {
        Date nowDate = DateUtils.getNowDate();
        List<BdmOrder> bdmOrders = bdmOrderMapper.selectCloseOrder(BdmOrderEnum.TIMEOUT.getType());

        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();

        //新增订单操作日志
        if (!CollectionUtils.isEmpty(bdmOrders)) {
            for (BdmOrder bdmOrder : bdmOrders) {
                log.info("订单号：{}", bdmOrder.getId());
                if (bdmOrder.getOrderType() == 2L) {
                    log.info("回退库存===============================");
                    cancelOrderTime(bdmOrder.getId());
                }
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(bdmOrder.getUserName());
                bdmOrderShipment.setCreateTime(nowDate);
                bdmOrderShipment.setUserId(bdmOrder.getUserId());
                bdmOrderShipment.setSoId(bdmOrder.getId());
                bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户订单超时未支付");
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.ORDER_CLOSURE.getType());
                bdmOrderShipments.add(bdmOrderShipment);
            }
        }
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束------------------
        bdmOrderMapper.closeOrder(BdmOrderEnum.TIMEOUT.getType());
    }

    /**
     * 超时订单
     */
    @Transactional
    public boolean cancelOrderTime(String orderId) {
        List<BdmOrderItem> bdmOrderItems = bdmOrderItemService.lambdaQuery().eq(BdmOrderItem::getOrderId, orderId).list();

        BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, orderId).one();
        //商城订单
        if (bdmOrder.getOrderType().equals(BdmGoodEnum.MALL_ORDER.getType())) {
            //回商城库存
            bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());
        }

        //云库存订单
        if (bdmOrder.getOrderType().equals(BdmGoodEnum.CLOUD_INVENTORY_ORDER.getType())) {
            List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();
                bdmCloudInventoryItem.setUserId(bdmOrder.getUserId());
                bdmCloudInventoryItem.setGoodId(Long.parseLong(bdmOrderItem.getSupplierGoodId()));
                bdmCloudInventoryItem.setNum(Long.parseLong(bdmOrderItem.getGoodCount()));
                bdmCloudInventoryItems.add(bdmCloudInventoryItem);
            }
            BdmCloudInventoryItem bdmCloudInventoryItem1 = new BdmCloudInventoryItem();
            bdmCloudInventoryItem1.setRelevantDocumentId(orderId);
            Date nowDate = DateUtils.getNowDate();
            for (BdmCloudInventoryItem bdmCloudInventoryItem2 : bdmCloudInventoryItems) {
                //扣减自己云库存
                ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();

                bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventoryItem2.getCloudInventoryId());//云库存id
                bdmCloudInventoryItem.setGoodId(bdmCloudInventoryItem2.getGoodId());//商品id
                bdmCloudInventoryItem.setGoodName(bdmCloudInventoryItem2.getGoodName());//商品名称
                bdmCloudInventoryItem.setGoodImg(bdmCloudInventoryItem2.getGoodImg());//商品图片
                bdmCloudInventoryItem.setNum(bdmCloudInventoryItem2.getNum());//商品数量
                bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   减少
                bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_DELIVERY_REQUEST_RETURN.getDescription());// 自提货到线下
                bdmCloudInventoryItem.setUserId(bdmOrder.getUserId());//用户id
                bdmCloudInventoryItem.setCorrelationUserId(bdmOrder.getUserId());//补货上下级  自己
                bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
                bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//进货状态 已完成
                bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
                bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
                bdmCloudInventoryItem.setCreateBy(bdmOrder.getUserId().toString());//创建用户
                bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
                bdmCloudInventoryItem.setUpdateBy(bdmOrder.getUserId().toString());//修改用户

                items.add(bdmCloudInventoryItem);
                log.info("云库存明细：{}", items);
                //记录云库存明细
                bdmCloudInventoryItemService.saveBatch(items);
            }
            //回云库存
            bdmCloudInventoryService.addOrRollBackStock(bdmCloudInventoryItems, BdmGoodEnum.ADD.getType());
        }


        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        //新增订单操作日志
        if (!ObjectUtils.isEmpty(bdmOrder)) {
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户取消订单");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.ORDER_CLOSURE.getType());
            bdmOrderShipments.add(bdmOrderShipment);
        }
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束------------------

        //修改订单状态
        return this.lambdaUpdate().eq(BdmOrder::getId, orderId).set(BdmOrder::getOrderStatus, BdmOrderEnum.CLOSE.getType()).update();
    }

    /**
     * 查询订单详情
     */
    @Override
    public AppletOrderDetailsVo orderDetails(String orderId) {
        BdmOrder one = this.lambdaQuery().eq(BdmOrder::getId, orderId).one();
        if (ObjectUtils.isEmpty(one)) {
            throw new RuntimeException("订单不存在");
        }
        AppletOrderDetailsVo appletOrderDetailsVo = BeanUtil.copyProperties(one, AppletOrderDetailsVo.class);

        List<AppletBdmOrderItemVo> appletBdmOrderItemVos = bdmOrderMapper.orderDetails(orderId);
        appletOrderDetailsVo.setAppletBdmOrderItemVos(appletBdmOrderItemVos);
        return appletOrderDetailsVo;
    }


    /**
     * 取消订单
     */
    @Override
    @Transactional
    public boolean cancelOrder(String orderId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<BdmOrderItem> bdmOrderItems = bdmOrderItemService.lambdaQuery().eq(BdmOrderItem::getOrderId, orderId).list();

        BdmOrder bdmOrder = this.lambdaQuery().eq(BdmOrder::getId, orderId).one();
        //商城订单
        if (bdmOrder.getOrderType().equals(BdmGoodEnum.MALL_ORDER.getType())) {
            //回商城库存
            bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());
        }

        //云库存订单
        if (bdmOrder.getOrderType().equals(BdmGoodEnum.CLOUD_INVENTORY_ORDER.getType())) {
            List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();
                bdmCloudInventoryItem.setUserId(bdmOrder.getUserId());
                bdmCloudInventoryItem.setGoodId(Long.parseLong(bdmOrderItem.getSupplierGoodId()));
                bdmCloudInventoryItem.setNum(Long.parseLong(bdmOrderItem.getGoodCount()));
                bdmCloudInventoryItems.add(bdmCloudInventoryItem);
            }
            BdmCloudInventoryItem bdmCloudInventoryItem1 = new BdmCloudInventoryItem();
            bdmCloudInventoryItem1.setRelevantDocumentId(orderId);
            Date nowDate = DateUtils.getNowDate();
            for (BdmCloudInventoryItem bdmCloudInventoryItem2 : bdmCloudInventoryItems) {
                //扣减自己云库存
                ArrayList<BdmCloudInventoryItem> items = new ArrayList<>();
                BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();

                bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventoryItem2.getCloudInventoryId());//云库存id
                bdmCloudInventoryItem.setGoodId(bdmCloudInventoryItem2.getGoodId());//商品id
                bdmCloudInventoryItem.setGoodName(bdmCloudInventoryItem2.getGoodName());//商品名称
                bdmCloudInventoryItem.setGoodImg(bdmCloudInventoryItem2.getGoodImg());//商品图片
                bdmCloudInventoryItem.setNum(bdmCloudInventoryItem2.getNum());//商品数量
                bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   减少
                bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_DELIVERY_REQUEST_RETURN.getDescription());// 自提货到线下
                bdmCloudInventoryItem.setUserId(user.getUserId());//用户id
                bdmCloudInventoryItem.setCorrelationUserId(user.getUserId());//补货上下级  自己
                bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
                bdmCloudInventoryItem.setMoney(new BigDecimal("0"));//进货状态 已完成
                bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
                bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
                bdmCloudInventoryItem.setCreateBy(user.getUserId().toString());//创建用户
                bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
                bdmCloudInventoryItem.setUpdateBy(user.getUserId().toString());//修改用户

                items.add(bdmCloudInventoryItem);
                log.info("云库存明细：{}", items);
                //记录云库存明细
                bdmCloudInventoryItemService.saveBatch(items);
            }
            //回云库存
            bdmCloudInventoryService.addOrRollBackStock(bdmCloudInventoryItems, BdmGoodEnum.ADD.getType());
        }


        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        //新增订单操作日志
        if (!ObjectUtils.isEmpty(bdmOrder)) {
            BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
            bdmOrderShipment.setUserName(bdmOrder.getUserName());
            bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
            bdmOrderShipment.setUserId(bdmOrder.getUserId());
            bdmOrderShipment.setSoId(bdmOrder.getId());
            bdmOrderShipment.setParticulars("手机号为：" + bdmOrder.getPhoneNumber() + " 用户取消订单");
            bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.ORDER_CLOSURE.getType());
            bdmOrderShipments.add(bdmOrderShipment);
        }
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束------------------

        //修改订单状态
        return this.lambdaUpdate().eq(BdmOrder::getId, orderId).set(BdmOrder::getOrderStatus, BdmOrderEnum.CLOSE.getType()).update();
    }

    /**
     * 购买代理礼包的单品
     *
     * @param goodId
     */
    private void insertCloudInventory(Long goodId, Long userId, String orderId) {
        BdmAgentGiftPackage aPackage = new BdmAgentGiftPackage();
        aPackage.setGoodId(goodId);
        // 查询代理商品的单品信息
        List<BdmAgentGiftPackageDto> bdmAgentGiftPackageDtos = iBdmAgentGiftPackageService.selectBdmAgentGiftPackageList(aPackage);
        log.info("本次代理礼包的单品信息是.........{}", bdmAgentGiftPackageDtos);
        for (BdmAgentGiftPackageDto dto : bdmAgentGiftPackageDtos) {
            // 代理商品关联的单品信息
            List<BdmAgentGiftPackageDto.OneGood> oneGoods = dto.getOneGoods();
            for (BdmAgentGiftPackageDto.OneGood oneGood : oneGoods) {
                // 查询商品进货价 零售价信息
                BdmGood good = bdmGoodService.getById(oneGood.getOneGoodId());
                // 如果有该云库存商品增加该商品库存
                BdmCloudInventory inventory = bdmCloudInventoryService.lambdaQuery().eq(BdmCloudInventory::getUserId, userId).eq(BdmCloudInventory::getGoodId, goodId).one();
                if (inventory == null) {
                    inventory = new BdmCloudInventory();
                    inventory.setGoodId(oneGood.getOneGoodId());
                    inventory.setUserId(userId);
                    // 商品等级
                    Long productLevel = dto.getProductLevel();

                    // 共享
                    if (productLevel.equals(3L)) {
                        inventory.setStockPrice(good.getSharePrice());
                    }
                    // 联创
                    if (productLevel.equals(4L)) {
                        inventory.setStockPrice(good.getJoinPrice());
                    }
                    // 运营
                    if (productLevel.equals(5L)) {
                        inventory.setStockPrice(good.getOperationsPrice());
                    }
                    // 总裁
                    if (productLevel.equals(6L)) {
                        inventory.setStockPrice(good.getPresidentPrice());
                    }
                    inventory.setRetailPrice(good.getRetailPrice());
                    inventory.setProfit(inventory.getRetailPrice().subtract(inventory.getStockPrice()));
                    inventory.setGoodInventory(oneGood.getOneGoodNumber().toString());
                    inventory.setGoodImg(good.getGoodImg());
                    inventory.setGoodName(good.getGoodName());
                    inventory.setGoodSpecs(good.getGoodSpecs());
                    bdmCloudInventoryService.insertBdmCloudInventory(inventory);

                } else {
                    inventory.setGoodInventory((Long.parseLong(inventory.getGoodInventory()) + oneGood.getOneGoodNumber()) + "");
                    bdmCloudInventoryService.updateBdmCloudInventory(inventory);
                }
                BdmCloudInventoryItem item = new BdmCloudInventoryItem();
                item.setCloudInventoryId(inventory.getId());
                item.setGoodId(good.getGoodId());
                item.setGoodName(good.getGoodName());
                item.setGoodImg(good.getGoodImg());
                item.setNum(oneGood.getOneGoodNumber());
                item.setNumType(1L);
                item.setVariationType(good.getGoodName());
                item.setUserId(userId);
                item.setCorrelationUserId(0L);
                item.setRelevantDocumentId(orderId);
                item.setStockType(2L);
                iBdmCloudInventoryItemService.insertBdmCloudInventoryItem(item);
            }
        }
    }

    public void verifyNumber(Long inventoryVersion, Long userId, Long productId, int number) {
        // 若限购数量为 0，表示不限制，直接返回
        if (inventoryVersion == 0) {

        } else {
            // 限购数量
            ArrayList<Long> orderStatus = new ArrayList<>();
            orderStatus.add(5L);
            orderStatus.add(6L);
            List<BdmOrder> orderList = this.lambdaQuery().eq(BdmOrder::getUserId, userId).notIn(BdmOrder::getOrderStatus, orderStatus).list();
            if (!CollectionUtils.isEmpty(orderList)) {
                List<String> orderIds = orderList.stream().map(BdmOrder::getId).collect(Collectors.toList());
                int productCount = bdmOrderItemService.lambdaQuery().in(BdmOrderItem::getOrderId, orderIds)
                        .list()
                        .stream()
                        .filter(item -> productId.equals(Long.parseLong(item.getSupplierGoodId()))).mapToInt(item -> Integer.parseInt(item.getGoodCount())).sum();
                if (productCount != 0 && (productCount + number) > inventoryVersion) {
                    throw new RuntimeException("vip礼包超过限购次数");
                }
            }
        }
    }
}
